package ua_gov_energy_vkek_icelineacct.service.mail;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.ejb.EJB;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
import ua_gov_energy_vkek_icelineacct.mail.SendException;
import ua_gov_energy_vkek_icelineacct.mail.Sender;
import ua_gov_energy_vkek_icelineacct.model.User;
import ua_gov_energy_vkek_icelineacct.service.DataException;
import ua_gov_energy_vkek_icelineacct.service.UsersFacade;

@Path("/mail")
public class UsersSenderRS {

    @EJB
    UsersFacade facade;

    @POST
    public Response sendMail(@FormParam("idUser") int idUser) {
        try {
            User user = facade.get(idUser);
            if (user == null) {
                throw new DataException("user not found for id=" + idUser);
            }
            Properties mailprops = getMailProps();
            String content = buildMailContent(user);
            Sender.MailMeta mm = new Sender.MailMeta(mailprops);
            mm.setSubj(mm.getSubj() + " [" + user.getLogin()+"]");
            Sender sender = new Sender();
            sender.send(mailprops, mm, content);

            return Response.status(Response.Status.OK).build();
        } catch (DataException de) {
            return buildErrResponse(Response.Status.BAD_REQUEST, de);
        } catch (IOException ioe) {
            return buildErrResponse(Response.Status.INTERNAL_SERVER_ERROR, ioe);
        } catch (SendException se) {
            return buildErrResponse(Response.Status.SERVICE_UNAVAILABLE, se);
        }
    }

    private Response buildErrResponse(Response.Status status, Exception e) {
        Map m = new HashMap();
        m.put("message", e.getMessage());
        return Response.status(status).entity(m).build();
    }

    public String buildMailContent(User user) {
        StringBuilder sb = new StringBuilder("user account info");
        sb.append("\n\n");
        sb.append("User: ").append(getEmpty(user.getFirstName()))
                .append(" ")
                .append(getEmpty(user.getSecondName()))
                .append(" ")
                .append(getEmpty(user.getLastName()));
        sb.append("\n");
        sb.append("Login: ").append(getEmpty(user.getLogin()));
        sb.append("\n");
        sb.append("Group: ").append(getEmpty(user.getUserGroup()));
        sb.append("\n");
        sb.append("Enabled?: ").append(getEmpty(user.getEnabled()));
        return sb.toString();
    }

    private String getEmpty(String val) {
        return val == null ? "" : val;
    }

    private Properties getMailProps() throws IOException {
        Properties ret = new Properties();
        InputStream buf = this.getClass()
                .getClassLoader()
                .getResourceAsStream("META-INF/mail.properties");
        ret.load(buf);
        return ret;
    }
}
